import requests
from django.core.cache import cache
import random

from common.errors import VcodeExist
from worker import celery_app, call_by_worker
from swiper import config


def gen_verify_code(length=6):
    """产生验证码"""
    min_value = 10 ** (length - 1)
    max_value = 10 ** length
    number = random.randrange(min_value, max_value)
    return number

import time

# @call_by_worker
def send_verify_code(phonenum):
    """发送短信验证码"""
    key = 'VCode-%s' % phonenum
    if not cache.has_key(key):
        vcode = gen_verify_code()
        params = config.HY_SMS_PARAMS.copy()
        params['mobile'] = phonenum
        params['content'] = config.HY_SMS_PARAMS['content'] % vcode
        response = requests.post(config.HY_SMS_URL, data=params)
        # time.sleep(30)
        # print('异步任务结束')
        print(vcode)
        cache.set(key, vcode, 300)
        return response
    else:
        raise VcodeExist


# send_verify_code = celery_app.task(send_verify_code).delay


def check_vcode(phonenum, vcode):
    """检查验证码"""
    cached_vcode = cache.get('VCode-%s' % phonenum)
    print(vcode, cached_vcode)
    print(type(vcode), type(cached_vcode))
    return str(cached_vcode) == vcode
